'use strict';

const { Service } = require('egg');
const ModelName = 'GiftSendItem'
class RouterService extends Service {
  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        { model: this.ctx.model.Gift },
        { model: this.ctx.model.Member }
      ]
    });
  }

  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        { model: this.ctx.model.Gift },
        { model: this.ctx.model.Member }
      ]
    });
  }
  async publishList(where) {
    return this.ctx.model[ModelName].findAll({
      where,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        { model: this.ctx.model.Gift },
        { model: this.ctx.model.Member }
      ]
    });
  }
  async findOne(where) {
    return this.ctx.model[ModelName].findOne({
      // where id 或者 code
      where,
      include: [
        { model: this.ctx.model.Gift },
        { model: this.ctx.model.Member }
      ]
    });
  }
  async findOneByCode(code) {
    return this.ctx.model[ModelName].findOne({
      where: {
        code,
      },
      include: [
        { model: this.ctx.model.Gift },
        { model: this.ctx.model.Member }
      ]
    });
  }
  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {
    return this.ctx.model[ModelName].create(data);
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    // 扣减gift表中库存
    const gift = await this.ctx.model.Gift.findOne({
        where: {
            id: data.gift_id
        }
    })
    if (gift) {
      if (gift.store_count <= 0) {
        throw new Error('库存不足')
      }
        await this.ctx.model.Gift.update({
            store_count: gift.store_count - 1
        }, {
            where: {
                id: data.gift_id
            }
        })
    }
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }
  async get(id, data) {
    console.log(id)
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }
  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }
}

module.exports = RouterService;
